param ( [string] $DatasetDir
      , [string] $ConfigFile=$DefaultDatabaseConfigFile
      , [string] $EnvironmentName=$DefaultDatabaseEnv
			, [string] $ServerName=$DefaultServerName
			, [string] $DatabaseName=$DefaultDatabaseName
			, [string] $Username=$DefaultUsername
			, [string] $Password=$DefaultPassword
			, [switch] $Whatif
			)

. Resolve-DbDeploymentParms

$conn = $PSSqlConnectionClass.New($ProviderParms)

$TablesSql = $PSSqlCommandClass.New($conn)
$TablesSql.Command.CommandText = @"
SELECT ss.name as SchemaName
     , so.name as TableName
  FROM sys.objects so
  JOIN sys.schemas ss ON so.schema_id = ss.schema_id
 WHERE type in (N'U')
   AND ss.name <> 'DBFRAMEWORK'
"@

$TableNames = @()
$reader = $TablesSql.Command.ExecuteReader()
while ($reader.Read())
{
	$TableNames += ("{0}.{1}" -f $reader.GetValue(0),$reader.GetValue(1))
}

$TableListForm,$CheckList = . Get-CheckboxSelectForm -ObjectList $TableNames -Title "Select Tables to use in Datasets" 

$files = dir $DatasetDir -Filter *.xml | %{$_.Name.SubString(0,$_.Name.Length-$_.Extension.Length)}

foreach ($file in $files)
{
	$idx = $CheckList.Items.IndexOf($file)
	if ($idx -ge 0)
	{
		$CheckList.SetItemChecked($idx,$TRUE)
	}
}

$result = $TableListForm.ShowDialog()

if($result -eq "OK")
{
	$SelectedTableNames = $CheckList.CheckedIndices | %{$CheckList.Items[$_]}
	
	$FilesToBeDeleted = $files | ?{-not ($SelectedTableNames -contains $_)}
	$FilesToBeAdded = $SelectedTableNames | ?{-not ($files -contains $_)}
	
	
	foreach ($file in $FilesToBeDeleted)
	{
		$filepath = Join-Path $DatasetDir "$($file).xml"
		Remove-Item -Path $filepath -WhatIf:$whatif
	}
	
	foreach ($file in $FilesToBeAdded)
	{
		$filepath = Join-Path $DatasetDir "$($file).xml"
		if ($whatif)
		{
			Write-Host ('What if: Performing operation "Create File" {0}' -f $filepath)
		}
		else
		{
			"" | Set-Content -Path $filepath
		}
	}
}
